package com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzcpxx.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzcpxx.base.attachment.service.AttachmentInfoService;
import com.css.fxfzcpxx.common.utils.UpdateUtil;
import com.css.fxfzcpxx.modules.earthquakeDisaster.entity.EarthquakeDisaster;
import com.css.fxfzcpxx.modules.earthquakeDisaster.repository.EarthquakeDisasterRepository;
import com.css.fxfzcpxx.modules.earthquakeDisaster.vo.EarthquakeDisasterVO;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.entity.JcStrongCatalog;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.param.FindByParam;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.param.HistoricalSeismicEventParam;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.entity.MapData;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.repository.HistoricalSeismicEventRepository;
import com.css.fxfzcpxx.modules.infoRetrieval.historicalSeismicInfo.service.HistoricalSeismicEventService;
import com.css.fxfzcpxx.modules.util.JCSJLszhResp;
import com.css.fxfzcpxx.util.PlatformObjectUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author: zhangSongRui
 * @CreateTime: 2023/04/07
 * @Description: 历史地震事件
 */
@Slf4j
@Service
public class HistoricalSeismicEventServiceImpl implements HistoricalSeismicEventService {

    @Resource
    private HistoricalSeismicEventRepository historicalSeismicEventRepository;
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private EarthquakeDisasterRepository earthquakeDisasterRepository;

    @Resource
    private AttachmentInfoService attachmentInfoService; // 附件

    //查询三年内四级以上的历史地震事件
    @Override
    public List<MapData> queryAllByParam() {
        JCSJLszhResp<List<MapData>> allByParam = getAllByParam();
        List<MapData> data = allByParam.getData();
        return data;
    }

    //分页
    @Override
    public Map<String, Object> getPage(int curPage, int pageSize, HistoricalSeismicEventParam param) {
        JCSJLszhResp<Map<String, Object>> page = getPag(curPage, pageSize,param);
        Map<String, Object> data = page.getData();
        return data;
    }

    @Override
    public EarthquakeDisasterVO findByParam(FindByParam param) {
        EarthquakeDisasterVO earthquakeDisasterVO = new EarthquakeDisasterVO();
        EarthquakeDisaster byId = earthquakeDisasterRepository.findByParam(param);
        if(PlatformObjectUtils.isNotEmpty(byId)){
            UpdateUtil.copyNullProperties(byId, earthquakeDisasterVO);
            //典型震害照片
            if (!StringUtils.isEmpty(byId.getJedsZhzp())){
                String[] split = byId.getJedsZhzp().split(",");
                List<AttachmentInfoEntity> jedsZhzpList = new ArrayList<>();
                for (String s : split) {
                    //根据id和文件名获取真实的放在磁盘上的文件
                    AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(s);
                    jedsZhzpList.add(attachmentInfoEntity);
                }
                earthquakeDisasterVO.setJedsZhzpList(jedsZhzpList);
            }
            //等震线（图片）
            if (!StringUtils.isEmpty(byId.getIsolinePic())){
                String[] split = byId.getIsolinePic().split(",");
                List<AttachmentInfoEntity> isolinePicList = new ArrayList<>();
                for (String s : split) {
                    //根据id和文件名获取真实的放在磁盘上的文件
                    AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(s);
                    isolinePicList.add(attachmentInfoEntity);
                }
                earthquakeDisasterVO.setIsolinePicList(isolinePicList);
            }
            //烈度图
            if (!StringUtils.isEmpty(byId.getIntensityMap())){
                String[] split = byId.getIntensityMap().split(",");
                List<AttachmentInfoEntity> intensityMapList = new ArrayList<>();
                for (String s : split) {
                    //根据id和文件名获取真实的放在磁盘上的文件
                    AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(s);
                    intensityMapList.add(attachmentInfoEntity);
                }
                earthquakeDisasterVO.setIntensityMapList(intensityMapList);
            }
            //附件
            if (!StringUtils.isEmpty(byId.getAttachment())){
                String[] split = byId.getAttachment().split(",");
                List<AttachmentInfoEntity> attachmentList = new ArrayList<>();
                for (String s : split) {
                    //根据id和文件名获取真实的放在磁盘上的文件
                    AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(s);
                    attachmentList.add(attachmentInfoEntity);
                }
                earthquakeDisasterVO.setAttachmentList(attachmentList);
            }
            return earthquakeDisasterVO;
        }
        return null;
    }

    @Override
    public Map<String, Object> findById(String id) {
        Map<String, Object> findById = getFindById(id);
        return findById;
    }

    //查询三年内四级以上的历史地震事件
    private JCSJLszhResp<List<MapData>> getAllByParam(){
        MultiValueMap<String, Object> param = new LinkedMultiValueMap();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("sjxtRestUrl") + "/datacenter/jcStrongCatalog/queryAllByParam";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        HttpEntity<MultiValueMap> r = new HttpEntity<>(param, headers);
        JCSJLszhResp<List<MapData>> response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, r, JCSJLszhResp.class).getBody();
        } catch (
                RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            log.info("error -> exception: {}", e);
        }
        return response;
    }
    private JCSJLszhResp<Map<String, Object>> getPag(int lon,int lat,HistoricalSeismicEventParam par){
        MultiValueMap<String, Object> param = new LinkedMultiValueMap();
        String mapping="/datacenter/jcStrongCatalog/getPage?lon=" + lon
                + "&lat=" + lat
                + "&startTime=" + par.getStartTime()
                + "&endTime=" + par.getEndTime()
                + "&startMagnitude=" + par.getStartMagnitude()
                + "&endMagnitude=" + par.getEndMagnitude()
                + "&startLongitude=" + par.getStartLongitude()
                + "&endLongitude=" + par.getEndLongitude()
                + "&startLatitude=" + par.getStartLatitude()
                + "&endLatitude=" + par.getEndLatitude()
                + "&location=" + par.getLocation()
                + "&province=" + par.getProvince()
                + "&city=" + par.getCity()
                + "&district=" + par.getDistrict()
                + "&eventAbbrevia=" + par.getEventAbbrevia()
                + "&town=" + par.getTown()
                + "&geom=" + par.getGeom();
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("sjxtRestUrl") + mapping;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        HttpEntity<MultiValueMap> r = new HttpEntity<>(param, headers);
        JCSJLszhResp<Map<String, Object>> response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, r, JCSJLszhResp.class).getBody();
        } catch (
                RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            log.info("error -> exception: {}", e);
        }
        return response;
    }
    //根据条件查询
    private Map<String, Object> getFindById(String id){
        String mapping="/datacenter/jcStrongCatalog/findById/"+id+"";
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String url = configGroup.getProperty("sjxtRestUrl") + mapping;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        JSONObject valueMap = new JSONObject();
        HttpEntity<JSONObject> r = new HttpEntity<>(valueMap, headers);
        Map<String, Object> map=new HashMap<>();
        JSONObject response = null;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, r, JSONObject.class).getBody().getJSONObject("data");
            if(response.isEmpty()){
                return  map;
            }
            // 使用Jackson库将JSONObject转换为Map
            ObjectMapper objectMapper = new ObjectMapper();
            map = objectMapper.readValue(response.toString(), Map.class);
        } catch (Exception e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", valueMap);
            log.info("error -> exception: {}", e);
        }
        return map;
    }
}
